package com.ys.controller.api.finance;

import com.bo.dto.NameValueDto;
import com.ys.config.MenuId;
import com.ys.entity.finance.TcwCapitalBusinessCost;
import com.ys.entity.finance.TcwWanliOtherPayment;
import com.ys.entity.sys.YsCol;
import com.ys.enume.finance.TcwWanliOtherPaymentEnum;
import com.ys.service.finance.TcwCapitalBusinessCostService;
import com.ys.service.flow.YspTaskService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.PdfService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 预付款认领单(运营费用认领单)
 */
@Controller
@RequestMapping("/api/inter/tcwCapitalBusinessCost")
public class ApiInterTcwCapitalBusinessCostController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTcwCapitalBusinessCostController.class);

    @Autowired
    private CommonApiService<TcwCapitalBusinessCost> commonApiService;

    @Autowired
    private TcwCapitalBusinessCostService tcwCapitalBusinessCostService;

    @Autowired
    private YspTaskService yspTaskService;

    @Autowired
    private PdfService pdfService;


    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TcwCapitalBusinessCost setSeachSql(TcwCapitalBusinessCost cond) throws Exception{

        cond = tcwCapitalBusinessCostService.setSeachSql(cond);
        return  cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions("tcwCapitalBusinessCost:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TcwCapitalBusinessCost cond,String conditions
    ){
        try {
            cond = setSeachSql(cond);
            cond = commonApiService.dataAuth(MenuId.TCW_CapitalBusinessCost, cond);
            //查询条件
            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_createUserName");//制单人
            if (nameLinked != null){
                cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
            }
            LayuiTableVoJA setList = commonApiService.searchLay(cond);

            return setList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcwCapitalBusinessCost cond,String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = commonApiService.dataAuth(MenuId.TCW_CapitalBusinessCost, cond);
            cond = setSeachSql(cond);
            //查询条件
            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_createUserName");//制单人
            if (nameLinked != null){
                cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
            }
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MenuId.TCW_CapitalBusinessCost)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            ExportExcelUtils<TcwCapitalBusinessCost> util = new ExportExcelUtils<>(new TcwCapitalBusinessCost());
            String toFilePath = util.exportExcel(listData, listField, "预付款认领单");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }



    /**
     * 新增
     */
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toSave(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //新增
            return tcwCapitalBusinessCostService.add(params,MenuId.TCW_CapitalBusinessCost);
        } catch (Exception e) {
            logger.error("新增出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 修改
     */
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //修改
            return tcwCapitalBusinessCostService.update(params,MenuId.TCW_CapitalBusinessCost);
        } catch (Exception e) {
            logger.error("修改出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 删除
     */
    @PostMapping("/toDel")
    @ResponseBody
    public R toDel(Long id){
        try {
            return tcwCapitalBusinessCostService.del(id);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 删除列表
     */
    @RequestMapping("/toDelByItem")
    @ResponseBody
    public R toDelByItem(HttpServletRequest request,@RequestParam("list") List<String> idList){
        try {
            //删除
            for (int i = 0; i < idList.size(); i++) {
                tcwCapitalBusinessCostService.toDelByItem(Long.parseLong(idList.get(i)));
            }
            return R.ok();
        } catch (Exception e) {
            logger.error("删除出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }

    @PostMapping("/flowPass")
    @ResponseBody
    public R flowPass(HttpServletRequest request, Long id){
        try {
            return tcwCapitalBusinessCostService.flowPass(id, ShiroUtils.getUserId());
        } catch (IllegalArgumentException e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 流转驳回
     */
    @PostMapping("/flowRefuse")
    @ResponseBody
    public R flowRefuse(HttpServletRequest request, Long id, String reason){

        try {
            TcwCapitalBusinessCost entity = new TcwCapitalBusinessCost().setId(id).queryFirst();
            return yspTaskService.flowRefuse(entity.getBid(), reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 流转驳回
     */
    @PostMapping("/flowInit")
    @ResponseBody
    public R flowInit(HttpServletRequest request, Long id, String reason){

        try {
            TcwCapitalBusinessCost entity = new TcwCapitalBusinessCost().setId(id).queryFirst();
            return yspTaskService.flowInit(entity.getBid(), reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 打印
     */
    @RequestMapping("/exportdy")
    @ResponseBody
    public R exportdy(HttpServletRequest request,@RequestParam("bid") String bid) throws Exception {
        List<Map<String, Object>> infoList = new TcwCapitalBusinessCost()
                .addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId ")
                .addField("U.UserId + '/' + U.UserName AS _ys_createUserName")//制单人
                .addField("U.DeptName AS deptName")//制单人部门
                .addField("FORMAT(A.CreateTime, 'yyyy-MM-dd HH:mm:ss') AS createTimeByStr")//创建时间

                .addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
                //.addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd HH:mm:ss') AS auditingTime")//审核时间
                .addField("CASE WHEN P.UpdateTime IS NULL AND A.EffectStock = 1 THEN FORMAT(A.UpdateTime, 'yyyy-MM-dd HH:mm:ss') ELSE FORMAT(P.UpdateTime, 'yyyy-MM-dd HH:mm:ss') END auditingTime")//审核时间

                .addLeftJoin("THR_OperateCompanyApply OCA ON OCA.Vgsbm = A.Vgsbm ")
                .addField("OCA.Vgsjc AS vgsjc,OCA.vgsmc AS vgsmc")//认领运营公司
                .addField("OCA.Cuser AS cuser")//运营人

                .addLeftJoin("TCW_CapitalBusinessCostSon S ON S.Pbid = A.Bid")//子表
                .addField("S.PaymentTime AS paymentTime")//付款时间
                .addField("S.PaymentAmount AS paymentAmount")//付款金額
                .addField("S.paymentAmount AS totalAmount")//付款总金额

                .addLeftJoin("THR_OperateCompanyBankInfo B ON B.Id = S.OperateCompanyBankInfoId")//运营公司银行账户管理
                .addField("B.Vid AS vid")//账户编码
                .addField("B.Vyhzhmc AS vyhzhmc")//付款银行户名
                .addField("B.Vkhh AS vkhh")//付款开户行
                .addField("B.Vyhzh AS vyhzh")//付款银行账号
                .addField("'运营服务→预付款' AS vjylx")//交易类型

                .addLeftJoin("TCW_CapitalRegisterClaim CRC ON CRC.Id = S.CapitalRegisterClaimId")//资金登记认领表
                .addLeftJoin("THR_OperateCompanyBankInfo BI ON BI.Id = CRC.OperateCompanyBankInfoId")//运营公司银行账户管理
                .addField("BI.Vyhzhmc AS paymentVyhzhmc")//登记银行户名
                .addField("BI.Vkhh AS paymentVkhh")//登记开户行
                .addField("BI.Vyhzh AS paymentVyhzh")//登记银行账号
                .addField("BI.AccountType AS accountType")//账户类型
                .setBid(bid)
                .where("B.Vyhzhmc is not null AND BI.Vyhzhmc is not null")
                .queryMap();

        if (infoList != null && infoList.size() > 0) {
            Map<String, Object> sonByOne = infoList.get(0);

            BigDecimal sonAmountTotal = BigDecimal.ZERO;
            for (Map<String, Object> son : infoList) {
                sonAmountTotal = sonAmountTotal.add(new BigDecimal(son.get("paymentAmount").toString()));
            }

            String nameStr = (sonByOne.get("vyhzhmc") != null ? sonByOne.get("vyhzhmc").toString() : "")
                    + "/" + (sonByOne.get("vyhzh") != null ? sonByOne.get("vyhzh").toString() : "")
                    + "/" + (sonByOne.get("vkhh") != null ? sonByOne.get("vkhh").toString() : "");

            List<NameValueDto> listData = new ArrayList<>();
            listData.add(new NameValueDto("单据编号", bid));
            listData.add(new NameValueDto("付款人", sonByOne.get("_ys_createUserName").toString()));
            listData.add(new NameValueDto("付款账号", nameStr));
            listData.add(new NameValueDto("付款时间", sonByOne.get("paymentTime").toString()));
            listData.add(new NameValueDto("付款金额", sonAmountTotal.toString()));
            listData.add(new NameValueDto("认领公司", sonByOne.get("vgsmc") != null ? sonByOne.get("vgsmc").toString() : ""));
            listData.add(new NameValueDto("付款说明", sonByOne.get("remark").toString()));
            String url = pdfService.generatePDF(bid, "预付款认领单", "福州逸博供应链有限公司", sonByOne.get("createTimeByStr").toString(), listData);
            return R.ok(url);
        } else {
            return R.error("未查询到要导出的数据");
        }
    }
}